/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package csci6450.chickenFriedFS.nuggetServer;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author jacobschoen
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            System.out.println("Nugget Server started");
            List<String> errors = new ArrayList<String>();
            boolean format = false;
            //get any arguments passed in
            for (int i = 0; i < args.length; i = i + 2) {
                //-cp client listener port
                //-mlp meta listener port
                //-mip meta server ip
                //-mslp meta server listener port
                //-nl  nugget server log location
                //-cc  number of chunks to initialize
                //-fs filestore location

                if (args[i].equals("-cp")) {
                    try {
                        RuntimeSettings.getInstance().setClientListenerPort(Integer.parseInt(args[i + 1]));
                    } catch (NumberFormatException numberFormatException) {
                        errors.add("-cp must be followed by a positive integer.");
                    }
                } else if (args[i].equals("-mlp")) {
                    try {
                        RuntimeSettings.getInstance().setMetaListenerPort(Integer.parseInt(args[i + 1]));
                    } catch (NumberFormatException numberFormatException) {
                        errors.add("-mlp must be followed by a positive integer.");
                    }
                } else if (args[i].equals("-mip")) {
                    RuntimeSettings.getInstance().setMetaServerIp(args[i + 1]);
                } else if (args[i].equals("-mslp")) {
                    try {
                        RuntimeSettings.getInstance().setMetaServerPort(Integer.parseInt(args[i + 1]));
                    } catch (NumberFormatException numberFormatException) {
                        errors.add("-mslp must be followed by a positive integer.");
                    }
                } else if (args[i].equals("-nl")) {
                    RuntimeSettings.getInstance().setNuggetServerLogLocation(args[i + 1]);
                } else if (args[i].equals("-cc")) {
                    try {
                        RuntimeSettings.getInstance().setNumberOfChunks(Integer.parseInt(args[i + 1]));
                    } catch (NumberFormatException numberFormatException) {
                        errors.add("-cc must be followed by a positive integer.");
                    }
                } else if (args[i].equals("-fs")) {
                    RuntimeSettings.getInstance().setFileStoreLocation(args[i + 1]);
                } else if (args[i].equals("-f")) {
                    format = args[i + 1].equalsIgnoreCase("yes") || args[i + 1].equalsIgnoreCase("y");
                } else if (args[i].equals("-rmp")) {
                    try {
                        RuntimeSettings.getInstance().setReplicationManagerPort(Integer.parseInt(args[i + 1]));
                    } catch (NumberFormatException numberFormatException) {
                        errors.add("-rmp must be followed by a positive integer.");
                    }
                } else if (args[i].equals("-rp")) {
                    try {
                        RuntimeSettings.getInstance().setReplicationPort(Integer.parseInt(args[i + 1]));
                    } catch (NumberFormatException numberFormatException) {
                        errors.add("-rp must be followed by a positive integer.");
                    }
                } else if (args[i].equals("-h")) {
                    errors.add("Following is the list of arguments that can be used to start the Nugget Server:");
                    errors.add("  '-cp'   The Port that this Nugget Server will listen for Client requests on.");
                    errors.add("  '-mlp'  The Port that this Nugget Server will listen for Meta Server Requests");
                    errors.add("          on.");
                    errors.add("  '-mip'  The IP or Address that the Meta Server this Nugget Server will join.");
                    errors.add("  '-mslp' The Port that the Meta Server this Nugget Server will join will");
                    errors.add("          listen for connections on.");
                    errors.add("  '-nl'   The Locaton this Nugget Server will place its log file at.");
                    errors.add("  '-cc'   The Number of chunks that this Nugget Server will initialize on");
                    errors.add("          creation. If there is an existing filestore, this will be ingnored");
                    errors.add("          unless the the '-f yes' options are included.");
                    errors.add("  '-fs'   The location of where the Nugget Server will place the actual");
                    errors.add("          filestore for the system.");
                    errors.add("  '-f'    This will delete the current filestore and log file and this nugget");
                    errors.add("          server will be refreshed.");
                    errors.add("          WARNING: This will lose any data currently stored in this nugget");
                    errors.add("          server.");
                    errors.add("  '-rmp'  The Port the Meta Server's Replication Manager listens on.");
                    errors.add("  '-rp'   The Port this Nugget Server will listen for other Nuggets servers on.");
                    errors.add("  '-h'    This will print the information above.");
                }

            }

            if (format) {
                //delete the log file and the file store location then tell user that it is done.
                File log = new File(RuntimeSettings.getInstance().getNuggetServerLogLocation());
                boolean success = log.delete();
                System.out.println("\nNugget Server Log has been deleted." + success);
                File fileStore = new File(RuntimeSettings.getInstance().getFileStoreLocation());
                success = fileStore.delete();
                System.out.println("\nNugget Server File Store has been deleted." + success);
            }

            try {
                java.net.InetAddress i = java.net.InetAddress.getLocalHost();
                System.out.println("Your parent OS is " + System.getProperty("os.name"));
                System.out.println("System IP address is: " + i.getHostAddress()); // IP address only
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (errors.size() == 0) {
                //means no problems so lets start this shindig
                NuggetServer.getInstance().start();
                listenForClientInput();
                System.exit(0);
            } else {
                //mean something went wrong tell the user
                for (int i = 0; i < errors.size(); i = i + 1) {
                    System.out.println(errors.get(i));
                }
                System.exit(0);
            }

        } catch (Exception ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            System.exit(0);
        }
    }

    private static void listenForClientInput() throws IOException {
        System.out.println("Welcome to the Nugget Server. It has been successfully started.");
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        String fromUser = new String();
        while (!fromUser.equalsIgnoreCase("EXIT")) {
            System.out.print("CFF$");
            fromUser = stdIn.readLine();
            if (!fromUser.equalsIgnoreCase("EXIT")) {
                System.out.println("CFFS does not recognize " + fromUser.trim() + ".");
            }
            System.out.println("Nugget Server has been shut down.");
        }

    }
}
